<template>
  <a-modal
    :open="open"
    :width="800"
    title="批量打折"
    centered
    :closable="false"
    ok-text="确认打折"
    :ok-button-props="{ disabled: !isCompleted }"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-table
      :columns="columns"
      :data-source="resourceData"
      :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
      bordered
      row-key="id"
      :pagination="false"
      :scroll="{ y: 280 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'advName'">
          <MedicineInfo :value="{ mc: record?.advName, gg: record?.spc, cj: record?.cj }" />
        </template>
        <template v-if="column.dataIndex === 'price'">
          <div>{{ formatAmount(record?.amount) }}</div>
        </template>
      </template>
    </a-table>
    <a-form :model="formState" class="form-style-flex mt-2">
      <a-form-item label="结算金额" class="w-1/2" v-bind="validateInfos.jsje">
        <a-input v-model:value="formState.jsje" v-input:float.2 placeholder="请输入结算金额" @blur="onBlur" />
      </a-form-item>
      <div class="w-1/2 flex justify-between mt-1.5 pl-3.5">
        <div>
          <span>折扣率:</span>
          <span>{{ formatAmount(discountRate) }}%</span>
        </div>
        <div>
          <span>合计金额:</span>
          <span>{{ '￥' + formatAmount(priceAll) }}</span>
        </div>
      </div>
      <a-form-item label="批准人" class="w-1/2" v-bind="validateInfos.pzr">
        <a-input v-model:value="formState.pzr" placeholder="请输入批准人" />
      </a-form-item>
      <a-form-item label="密码" class="w-1/2" v-bind="validateInfos.pwd">
        <a-input-password v-model:value="formState.pwd" placeholder="请输入密码" autocomplete="new-password" :max-length="20" />
        <template #prefix>
          <LockOutlined class="text-primary text-base" />
        </template>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, watch, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { LockOutlined } from '@ant-design/icons-vue'
import { formatAmount } from '@/utils/format.js'
import { post } from '@/utils/request'

const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  discountsData: {
    type: Array,
    default: () => []
  }
})
const resourceData = ref([])
const selectedRowKeys = ref([])
const selectedRows = ref([])
const ids = ref([])
const columns = [
  {
    title: '项目名称',
    dataIndex: 'advName',
    key: 'advName'
  },
  {
    title: '金额',
    dataIndex: 'price',
    key: 'price',
    width: '120px',
    align: 'right'
  }
]
const priceAll = ref(0)
const unitPrice = ref(0)
const discountRate = ref(0)

const formState = ref({
  jsje: '',
  pzr: '',
  pwd: ''
})
const rulesState = ref({
  jsje: [{ required: true, message: '请输入结算金额' }],
  pzr: [{ required: true, message: '请输入批准人' }],
  pwd: [{ required: true, message: '请输入密码' }]
})
const { isCompleted, validateInfos, resetFields } = useForm(formState, rulesState)
const onSelectChange = (keys, rows) => {
  selectedRowKeys.value = keys
  selectedRows.value = rows
  getPrice()
}

const onBlur = () => {
  if (+formState.value.jsje > 0) {
    discountRate.value = (Number(formState.value.jsje) / priceAll.value) * 100
  } else {
    discountRate.value = 0
  }
}

const onOk = async () => {
  const res = await post('/operation/opex/getDiscountPermisson', { empId: formState.value.pzr })
  if (res.code !== 0) return message.error(res.msg)
  // if (Number(discountRate.value) < res.data.discountPercent) {
  //   return message.error('不能超过最大折扣率')
  // }
  if (Number(discountRate.value) < res.data.discountPercent) {
    return message.error(`当前您可打的最高折扣为<${res.data.discountPercent}%>`)
  }
  if (Number(priceAll.value) - Number(formState.value.jsje) > res.data.maxDiscountAmount) {
    return message.error(`当前您的最高减免金额为<${formatAmount(res.data.maxDiscountAmount)}>元`)
  }
  formState.value.ids = ids.value
  formState.value.jsje = Number(formState.value.jsje)
  emit('success', { ...formState.value })
  onCancel()
}

const getPrice = () => {
  // 折扣率 = 金额/单价*数量*100%
  // 金额总和
  priceAll.value = selectedRows.value.reduce((pre, next) => {
    return pre + Number(next.amount)
  }, 0)
  // ids的集合
  ids.value = selectedRows.value.map((i) => {
    return i.ids
  })
  ids.value = ids.value.flat(2) //数据扁平化
  // 金额数量总和
  unitPrice.value = selectedRows.value.reduce((pre, next) => {
    return pre + Number(next.je)
  }, 0)
  nextTick(() => {
    // discountRate.value = (Number(unitPrice.value) / Number(priceAll.value)) * 100
  })
  // formState.value.jsje = formatAmount(unitPrice.value)
}

const onCancel = () => {
  emit('update:open', false)
}

watch(
  () => selectedRowKeys.value,
  () => {
    onBlur()
  }
)

watch(
  () => props.open,
  (val) => {
    if (val) {
      resourceData.value = [...props.discountsData]
      resourceData.value = resourceData.value.map((i, idx) => {
        return { ...i, id: idx + 1 }
      })
      selectedRows.value = [...resourceData.value]
      selectedRowKeys.value = selectedRows.value.map((i) => {
        return i.id
      })
      getPrice()
    } else {
      resetFields()
    }
  }
)
</script>
<style lang="less" scoped>
.discount-padding {
  padding-left: 61px;
}
</style>
